

package top.continew.admin.question.manger.base;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;

import java.util.List;
import java.util.function.Supplier;

/**
 * Created by
 *
 * @author sheng
 * @date 18/3/16.
 */
public class PageFactory {

    public static <T> List<T> page(Supplier<List<T>> supplier) {
        int pageNo;
        int pageSize;
        try {
            pageSize = Integer.parseInt(HttpKit.getRequestParameters().get("pageSize"));
            pageNo = Integer.parseInt(HttpKit.getRequestParameters().get("pageNo"));
        } catch (Exception e) {
            pageSize = 0;
            pageNo = 0;
        }
        String orderBy = sort();
        PageHelper.orderBy(orderBy);
        com.github.pagehelper.Page page = PageHelper.startPage(pageNo, pageSize);
        List<T> result = supplier.get();
        HttpKit.getRequest().setAttribute("total", page.getTotal());
        return result;
    }

    private static String sort() {
        StringBuilder orderBy = new StringBuilder();
        // 获取排序字段
        String sort = HttpKit.getRequestParameters().get("sort");
        if (StrUtil.isNotEmpty(sort)) {
            // asc_ctime_desc_utime
            String[] sorts = sort.split("_");
            for (int i = 0; i < sorts.length - 1; i = i + 2) {
                orderBy.append(sorts[i + 1]).append(" ").append(sorts[i]).append(" ");
            }
        }
        return orderBy.toString();
    }
}
